package org.zezs.sync.mongo.plugs.phone;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zezs.sync.mongo.Constants;
import org.zezs.sync.mongo.config.mongo.MongoUtil;
import org.zezs.sync.mongo.plugs.Plug;
import org.zezs.sync.mongo.plugs.bank.BankLocation;

import javax.script.ScriptException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class PhoneLocationCache extends Plug {

	public static Logger logger=LoggerFactory.getLogger(PhoneLocationCache.class);
	static Map<String, PhoneLocation> cacheMap = new HashMap<>(380000);

	public static Map<String, PhoneLocation> getPhoneLocation() {
        synchronized (cacheMap){
        	if(cacheMap.isEmpty()){
				logger.info("初始化手机位置信息");
				MongoCollection<Document> collection = MongoUtil.getMongoDb("paramConfig").getCollection("phone_location");
				List<BankLocation> bankLocations=new LinkedList<>();
				FindIterable<Document> documents = collection.find();
				MongoCursor<Document> iterator = documents.iterator();
				while (iterator.hasNext()){
					Document next = iterator.next();
					PhoneLocation phoneLocation = JSON.parseObject(next.toJson(), PhoneLocation.class);
					cacheMap.put(phoneLocation.getPhone_num(), phoneLocation);
				}
				logger.info("初始化手机位置信息结束{}",cacheMap.size());
			}
		}

		return cacheMap;
	}

	@Override
	public void init(NashornScriptEngine engine) {
		try {
			this.jsFile="/plugs/phone.js";
			initJs(engine);
			engine.invokeFunction("setPhoneCache", PhoneLocationCache.getPhoneLocation());
		} catch (ScriptException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}
}
